package admin

import (
	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
	"myai/core"
	"myai/core/types"
	"myai/handler"
	"myai/store/model"
	"myai/store/model/rsp"
	"myai/utils/resp"
	"time"
)

type DashboardHandler struct {
	handler.BaseHandler
}

func NewDashboardHandler(app *core.AppServer, db *gorm.DB) *DashboardHandler {
	return &DashboardHandler{BaseHandler: handler.BaseHandler{App: app, DB: db}}
}

// Stats 仪表盘接口
// Save godoc
// @Summary      仪表盘接口
// @Description  仪表盘接口，统计数据
// @Tags         后台管理-仪表盘接口
// @Accept       json
// @Produce      json
// @Success      200  {object}  types.BizVo{data=rsp.StatsResp}
// @Router       /api/admin/dashboard/stats [get]
// @Security AdminApiKeyAuth
func (h *DashboardHandler) Stats(c *gin.Context) {
	stats := rsp.StatsResp{}
	// 查询今日新增用户数量
	var userCount int64
	now := time.Now()
	zeroTime := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
	res := h.DB.Model(&model.User{}).Where("created_at > ?", zeroTime).Count(&userCount)
	if res.Error == nil {
		stats.Users = userCount
	}
	// 查询当天新增对话
	var chatCount int64
	res = h.DB.Model(&model.ChatItem{}).Where("created_at > ?", zeroTime).Count(&chatCount)
	if res.Error == nil {
		stats.Chats = chatCount
	}
	// 查询当天Token消耗
	var historyMessages []model.ChatMessage
	res = h.DB.Where("created_at > ?", zeroTime).Find(&historyMessages)
	for _, item := range historyMessages {
		stats.Tokens += item.Tokens
	}
	// 查询当天订单收入
	var orders []model.Order
	res = h.DB.Where("status = ?", types.OrderPaidSuccess).Where("created_at > ?", zeroTime).Find(&orders)
	for _, item := range orders {
		stats.Income += item.Amount
	}

	// 获取七天前的日期
	startDate := now.Add(-7 * 24 * time.Hour).Format("2006-01-02")
	var statsChart = make(map[string]map[string]float64)
	// 初始化
	var userStatistic, historyMessageStatistic, incomeStatistic = make(map[string]float64), make(map[string]float64), make(map[string]float64)
	for i := 0; i < 7; i++ {
		// 获取七天的日期字符串存储到map中
		var initTime = time.Date(now.Year(), now.Month(), now.Day()-i, 0, 0, 0, 0, now.Location()).Format("2006-01-02")
		userStatistic[initTime] = float64(0)
		historyMessageStatistic[initTime] = float64(0)
		incomeStatistic[initTime] = float64(0)
	}
	// 统计7天用户增加的曲线
	var users []model.User
	res = h.DB.Model(&model.User{}).Where("created_at > ?", startDate).Find(&users)
	if res.Error == nil {
		for _, item := range users {
			userStatistic[item.CreatedAt.Format("2006-01-02")] += 1
		}
	}

	// 统计7天Token消耗
	res = h.DB.Where("created_at > ?", startDate).Find(&historyMessages)
	for _, item := range historyMessages {
		historyMessageStatistic[item.CreatedAt.Format("2006-01-02")] += float64(item.Tokens)
	}

	// 统计最近7天的订单
	res = h.DB.Where("status = ?", types.OrderPaidSuccess).Where("created_at > ?", startDate).Find(&orders)
	for _, item := range orders {
		// 通过 decimal.NewFromFloat() 将 float64 转换为 decimal.Decimal 类型
		// 执行高精度加法运算 Add()
		// 最终通过 .Float64() 将结果转回 float64 类型
		incomeStatistic[item.CreatedAt.Format("2006-01-02")], _ =
			decimal.NewFromFloat(incomeStatistic[item.CreatedAt.Format("2006-01-02")]).Add(decimal.NewFromFloat(item.Amount)).Float64()
	}
	statsChart["users"] = userStatistic
	statsChart["historyMessage"] = historyMessageStatistic
	statsChart["orders"] = incomeStatistic
	stats.Chart = statsChart
	resp.SUCCESS(c, stats)
}
